#include <iostream>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <cstring>
#include <chrono>

#define SOCKET_PATH "/tmp/domain_socket"

int main() 
{
    // 创建 socket
    int client_sock = socket(AF_UNIX, SOCK_STREAM, 0);
    if (client_sock == -1) 
    {
        std::cerr << "Socket creation failed" << std::endl;
        return 1;
    }

    // 设置 socket 地址
    struct sockaddr_un addr;
    addr.sun_family = AF_UNIX;
    std::strcpy(addr.sun_path, SOCKET_PATH);

    // 连接到服务端
    if (connect(client_sock, (struct sockaddr*)&addr, sizeof(addr)) == -1) 
    {
        std::cerr << "Connect failed" << std::endl;
        close(client_sock);
        return 1;
    }

    char buffer[256];
    while(true)
    {
        sleep(1);
        memset(buffer,0x00,256);
        // / 记录发送的时间戳
        auto start_time = std::chrono::high_resolution_clock::now();
        uint64_t client_timestamp = std::chrono::duration_cast<std::chrono::nanoseconds>(start_time.time_since_epoch()).count();
        // 发送消息给服务端

        std::memcpy(buffer, &client_timestamp, sizeof(client_timestamp));
        const char* message = "Hello from client!";
        std::memcpy(buffer + sizeof(client_timestamp), message, std::strlen(message));

        send(client_sock, buffer, std::strlen(message)+sizeof(client_timestamp), 0);
        std::cout << "Message sent to server: " << message << std::endl;

        // // 接收服务端响应
        // char buffer[256];
        // ssize_t bytes_received = recv(client_sock, buffer, sizeof(buffer), 0);
        // if (bytes_received > 0) 
        // {
        //     buffer[bytes_received] = '\0'; // 确保字符串正确结束
        //     std::cout << "Received from server: " << buffer << std::endl;
        // }
    }

    // 关闭 socket
    close(client_sock);
    return 0;
}
